// 患者详情 业务逻辑开始以上废除
(() => {
  // 创建 Vue 实例并挂载到 id 为 main 的元素上
  new Vue({
    el: "#main",
    mixins: [mixin],
    data: {
      // 定义数据
      // 所有的病症列表
      //   {
      //   diseaseInfoId: "123", //int //病症主键ID
      //   name: "病症中文名称3", // 病症中文名称
      //   enName: "string //病症英文名称", // 病症英文名称
      //   createdDate: "date",
      //   createdBy: "string",
      //   updatedDate: "date",
      //   updatedBy: "string",
      // },
      doctorTestData: {
        docterId: "",
        doctorName: '',
        doctorType: "" // tdoctorInCharge-主管医生; dutyDoctor-值班医生
      },
      DiseaseData: [], //
      isedit: true,
      doctorList: [], // 医生列表
      showPickerVisible:false,
      currentDate:"",
      pickerType:"",
      icuTimePassed: false,
    },
    created () {
      toastr.options = {
        positionClass: 'toast-top-center'
      };
      // 初始化页面 需要获取当前医生信息
      this.initData()
      // 页面加载完成后执行的方法
      // this.getDiseaseData();
      this.getAllPatientList()
      this.getdoctorList()
    },
    methods: {
      // 显示选择器
      showPicker (type) {
        this.maxDate = this.getTodayEnd()
        this.pickerType = type; // 设置选择器类型
        this.currentDate = this.getValueByPath(this,type) ? dayjs(this.getValueByPath(this,type)).toDate() : "" ;
        this.showPickerVisible = true; // 显示选择器
      },
      onConfirm(value){
        this.setValueByPath(this,this.pickerType,dayjs(value).format('YYYY-MM-DD HH:mm:ss'),"")
        this.showPickerVisible = false; // 关闭选择器
        this.icuTimePassed = false;
      },
      initData () {
        // 获取医生信息
        const doctorData = sessionStorage.getItem("doctorTestData")
      if (doctorData) {
        Object.assign(this.doctorTestData, JSON.parse(doctorData))
        // 根据当前医生信息 获取所有患者信息
      }
        const patientInfoId = sessionStorage.getItem("patientInfoId")
        this.getPaitentDetail(patientInfoId)
      },
      doctorChange(){
        if(this.patientInfo.doctorInfoId){
         let data =  this.doctorList.find((item) => item.doctorInfoId == this.patientInfo.doctorInfoId)
         if(data){
          this.patientInfo.doctorName = data.name
         }
        }
      },
      // 定义方法
      getdoctorList () {
        try {
          const doctorTestData = sessionStorage.getItem("doctorTestData")
          const { hospitalInfoId } = JSON.parse(doctorTestData)
          const URL = "/doctor/list/all?hospitalInfoId=" + hospitalInfoId;
          fetch(apiUrl + URL, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ hospitalInfoId: hospitalInfoId })
          })
            .then((response) => {
              return response.json();
            })
            .then((data) => {
              if (data.code == "200") {
                this.doctorList = data.data
              } else {
                toastr.error(data.msg);
              }
            })
        } catch (error) {
          console.log(error)
        }
      },
      // 获取患者详情 
      getPaitentDetail (patientInfoId) {
        const URL = "/patient/detail?patientInfoId=" + patientInfoId;
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          // body: JSON.stringify({
          //   patientInfoId: patientInfoId,
          // })
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              // 更新一下患者id方便切换页面做 病人信息查询
              sessionStorage.setItem("patientInfoId", patientInfoId)
              this.patientInfo.patientDiseaseDetailList = []
              // let endata = {
              //   patientId: this.Encryption(data.data.patientId),
              //   name: this.Encryption(data.data.name)
              // }
              Object.assign(this.patientInfo, data.data)
              // this.getDiseaseData()
              console.log(this.patientInfo, "患者信息")
            } else {
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },

      // 切换患者信息 
      changePatient () {
        $('#staticBackdrop').modal('show');
      },
      changePatientHander (item) {
        // 确认选择患者 更新患者信息 并通过患者id查询当前患者基础信息及病症信息
        this.getPaitentDetail(item.patientInfoId)
        $('#staticBackdrop').modal('hide');
      },
      // 跳转到患者列表 
      addPatient () {
        window.location.href = "addPatient.html"
      },
      // 获取所有的病症
      async getDiseaseData () {
        const URL = "/disease/list";
        await fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {

            if (data.code === 200) {
              this.DiseaseData = data.data ?? []
              // 3患者的病症 patientDiseaseDetailList 同病症列表做对比 还原  value值做回显
              let disList = []
              this.DiseaseData.map(item => {
                this.patientInfo.patientDiseaseDetailList.map(items => {
                  if (item.diseaseInfoId == items.diseaseInfoId) {
                    disList.push({ name: item.name, enName: item.enName, value: items.value, patientDiseaseInfoId: items.patientDiseaseInfoId, diseaseInfoId: items.diseaseInfoId })
                    // "patientDiseaseInfoId":"int //病患病症信息主键ID【必须】",
                    // "diseaseInfoId":"int //病症信息主键【必须】",
                    // Object.assign(item, items)
                  }
                })
                // return item
              })
              this.patientInfo.patientDiseaseDetailList = disList
            } else {
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },
      editHander (e) {
        this.isedit = !this.isedit
        if (e) {
          this.initData()
        }
      },
      admissionTimeHander(e){
        if(this.patientInfo.firstIcuAdmissionTime && e){
          if(dayjs(e).isAfter(dayjs(this.patientInfo.firstIcuAdmissionTime))){
            // 判断 首次ICU入院时间 是否在 入院时 之后
            this.patientInfo.admissionTime = ""
            toastr.error('患者入院时间必须在患者首次入住ICU时间之前！');
            return
          }
        }
      },
      firstIcuAdmissionTimeHander(e){
        if(this.patientInfo.admissionTime && e){
          if(dayjs(this.patientInfo.admissionTime).isAfter(dayjs(e))){
            // 判断 首次ICU入院时间 是否在 入院时 之后
            this.patientInfo.firstIcuAdmissionTime = ""
            toastr.error('患者首次入住ICU时间必须在患者入院时间之后！');
            return
          }else if(dayjs(this.patientInfo.firstIcuAdmissionTime).diff(dayjs(this.patientInfo.admissionTime), 'day') > 15){
            // 2.入院和入icu 不超过15天
            toastr.error('患者首次入住ICU时间和患者入院时间之间不能超过15天！');
          }
        }
      },
      subeditHander () {
        if (!this.patientInfo.name) {
          toastr.error('请输入患者名字！');
          return
        } else if (!this.patientInfo.patientId) {
          toastr.error('请输入患者ID！');
          return
        } else if (!this.patientInfo.admissionTime) {
          toastr.error('请输入患者入院时间！');
          return
        } else if (!this.patientInfo.firstIcuAdmissionTime) {
          toastr.error('请输入患者首次ICU入院时间！');
          return
        }else if(dayjs(this.patientInfo.admissionTime).isAfter(dayjs(this.patientInfo.firstIcuAdmissionTime))){
          // 判断 首次ICU入院时间 是否在 入院时 之后
          toastr.error('患者首次入住ICU时间必须在患者入院时间之后！');
          return
        }else if (dayjs(this.patientInfo.firstIcuAdmissionTime).diff(dayjs(this.patientInfo.admissionTime), 'day') > 15 && !this.icuTimePassed) {
          vant.Dialog.confirm({
            title: '提示',
            message: '患者首次入住ICU时间和患者入院时间之间超过15天！是否继续？',
          })
            .then(() => {
              this.icuTimePassed = true
              this.subeditHander()
            })
            .catch(() => {
              this.icuTimePassed = false
            });
          return
      }else if (!this.patientInfo.age) {
          toastr.error('请输入患者年龄！');
          return
        }else if (!this.isPositiveInteger(this.patientInfo.age)) {
          // 判断患者年龄是否为数字
          toastr.error('请输入合法年龄！');
          return
        }else if (this.patientInfo.age > 125 || this.patientInfo.age < 18) {
          // 判断患者年龄是否在 18-125
          toastr.error('患者年龄区间为18-125岁！');
          return
        } else if (!this.patientInfo.gender) {
          toastr.error('请输入患者性别！');
          return
        } else if(!this.patientInfo.doctorInfoId){
          toastr.error('请选择医生！');
          return
        }
        const param = {
          "patientInfoId": this.patientInfo.patientInfoId, //"int //病患信息主键ID【必须】",
          "doctorInfoId": this.patientInfo.doctorInfoId, //"int //医生主键【必须】",
          "hospitalInfoId": this.patientInfo.hospitalInfoId, //"int //医院信息主键ID",
          "patientId": this.patientInfo.patientId, //"string //患者ID【必须】",
          "name": this.patientInfo.name, //"string //患者名称【必须】",
          "gender": this.patientInfo.gender, //"string //患者性别【必须】",
          "age": this.patientInfo.age, //"int //患者年龄【必须】",
          "admissionTime": this.patientInfo.admissionTime, //"date //患者入院时间【必须】",
          "firstIcuAdmissionTime":  dayjs(his.patientInfo.firstIcuAdmissionTime).format('YYYY-MM-DD HH:mm:ss'), //"date //首次入住ICU时间",
          "isDiagnosedWithSepsis": dayjs(this.patientInfo.isDiagnosedWithSepsis).format('YYYY-MM-DD HH:mm:ss'), //"string //是否确诊为脓毒症 1-是;0-否",
          "diagnosedTime": this.patientInfo.diagnosedTime, //"date //确诊为脓毒症的时间",
          "isPatientDischarged": this.patientInfo.isPatientDischarged, //"string //是否出院 1-是;0-否",
          "dischargedTime": this.patientInfo.dischargedTime, //"date //出院的时间",
          "patientDiseaseUpdateList": this.patientInfo.patientDiseaseDetailList.map(item => { return { value: item.value, patientDiseaseInfoId: item.patientDiseaseInfoId, diseaseInfoId: item.diseaseInfoId } }), //"string //更新人",
        }
        // this.patientInfo.patientDiseaseUpdateList = this.patientInfo.patientDiseaseDetailList.map(item => {return {value:item.value,patientDiseaseInfoId:item.patientDiseaseInfoId,diseaseInfoId:item.diseaseInfoId}})
        const URL = "/patient/upadte/info";
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(param)
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              toastr.success(data.msg ? data.msg : "操作成功！")
              this.getPaitentDetail(this.patientInfo.patientInfoId)
              this.isedit = true
            } else {
              toastr.error(data.msg ? data.msg : "操作失败！")
            }
          })
          .catch((error) => {
            console.error(error);
          });
      }
    },
  });
})();

